<?php

namespace App\Http\Admin\Controllers;

use App\Http\Admin\Response;
use App\Jobs\Queue;
use App\Models\UserGroup;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

class LoginController extends Controller
{
    protected $guard = 'jwtapis';

    /**
     * 默认中间件
     */
    public function __construct()
    {
        $this->middleware('refresh.token', ['except' => ['login']]);
    }

    /**
     * 用户登录
     */
    public function login(Request $request,JWTAuth $jwtAuth)
    {


        $credentials = $request->only('username', 'password');

        $credentials['usertype'] = 2;

        if($id = User::where(['username'=>$credentials['username'],'usertype'=>2])->value('id')){

            $verify = $this->loginVerify($jwtAuth,$credentials,$request,$id);

            if($verify['type']){
                return $verify['data'];
            }

            return Response::error($verify['data']);
        }

        return Response::error('账户不存在!');
    }

    /**
     * 登录验证规则
     */
    public function loginVerify($jwtAuth,$credentials,$request,$id)
    {
        $rkey = $credentials['username'].'number';

        $ckey = 'user'.$id.'token';

        if(Redis::get($rkey)<=5){

            if($token = $this->guard()->attempt($credentials)) {

                $oldtoken = Redis::get($ckey);

                if($oldtoken && $oldtoken != $token){

                    try{
                        $jwtAuth->setToken($oldtoken)->invalidate();
                    }catch (TokenExpiredException $exception) {
                        //token 用户token过期后拉黑token会抛出异常,此处捕获异常继续执行
                        //$exception->getMessage()
                    }

                    Redis::command('set',[$ckey,$token]);

                    return array('type'=>1,'data'=>$this->respondWithToken($token));

                }

                Redis::command('set',[$ckey,$token]);

                User::where(['id'=>$id])->update(['loginip'=>$request->getClientIp(),'extends'=>$id.'_'.date('Ymdhis').'_'.$request->getClientIp()]);

                return array('type'=>1,'data'=>$this->respondWithToken($token));
            }

            Redis::command('incr',[$rkey]);

            Redis::command('expire',[$rkey,3600]);

            return  array('type'=>false,'data'=>'用户账号密码错误,还有'.(6-Redis::get($rkey)).'次锁定!');
        }

        $retime = intval((Redis::command('pttl',[$rkey])  % (1000 * 60 * 60)) / (1000 * 60));

        return array('type'=>false,'data'=>'多次密码输入错误,账户已被锁定'.$retime.'分钟后解锁!');
    }

    /**
     * 获取用户信息
     */
    public function getuserinfo(Request $request)
    {
        if($data = Auth::guard($this->guard)->user()){

            $data['access'] = array(UserGroup::where('id',$data['groupid'])->value('unique'));

            if($data['groupid'] == 0){
                $data['access'] = UserGroup::pluck('unique','id')->toArray();
                $data['access'] = array_values($data['access']);
            }

            return response()->json($data);
        }else{

            return Response::error400('用户获取错误!');
        }
    }

    /**
     * 用户推出
     */
    public function logout(JWTAuth $jwtAuth)
    {
        $user = $this->guard()->user();

        $key = 'user'.$user['id'].'token';

        $oldtoken = Redis::get($key);

        $jwtAuth->setToken($oldtoken)->invalidate();

        Redis::command('del',[$key]);

        //$this->guard()->logout();
        return Response::success(['message' => '退出成功']);
    }

    //token 推出
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $this->guard()->factory()->getTTL() * 60,
            'status_code' => '200'
        ]);
    }

    //获取guard
    public function guard()
    {
        return Auth::guard($this->guard);
    }

}
